using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FreshCommonUtility.Dapper;
using FreshCommonUtility.SqlHelper;
using WeChatCmsCommon.EnumBusiness;
using WeChatModel.DatabaseModel;

namespace WeChatDataAccess
{
    /// <summary>
    /// 项目数据访问
    /// </summary>
    public class ProjectData : BaseData<long, ProjectModel>
    {
        /// <summary>
        /// 获取项目列表
        /// </summary>
        /// <param name="userIds">用户ID列表</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="name">项目名称（可选）</param>
        /// <returns></returns>
        public List<ProjectModel> GetModels(List<long> userIds, int pageIndex, int pageSize, string name = "")
        {
            var whereStr = new StringBuilder(" WHERE IsDel = @IsDel AND IsValid = @IsValid ");
            object param = new
            {
                IsDel = FlagEnum.HadZore.GetHashCode(),
                IsValid = FlagEnum.HadOne.GetHashCode()
            };

            if (userIds != null && userIds.Count > 0)
            {
                whereStr.Append(" AND UserId IN @UserIds ");
                if (!string.IsNullOrEmpty(name))
                {
                    whereStr.Append(" AND ProjectName LIKE @Name ");
                    param = new
                    {
                        IsDel = FlagEnum.HadZore.GetHashCode(),
                        IsValid = FlagEnum.HadOne.GetHashCode(),
                        UserIds = userIds.ToArray(),
                        Name = $"%{name}%"
                    };
                }
                else
                {
                    param = new
                    {
                        IsDel = FlagEnum.HadZore.GetHashCode(),
                        IsValid = FlagEnum.HadOne.GetHashCode(),
                        UserIds = userIds.ToArray()
                    };
                }
            }
            else if (!string.IsNullOrEmpty(name))
            {
                whereStr.Append(" AND ProjectName LIKE @Name ");
                param = new
                {
                    IsDel = FlagEnum.HadZore.GetHashCode(),
                    IsValid = FlagEnum.HadOne.GetHashCode(),
                    Name = $"%{name}%"
                };
            }

            using (var conn = SqlConnectionHelper.GetOpenConnection())
            {
                return conn.GetListPaged<ProjectModel>(pageIndex, pageSize, whereStr.ToString(), "Sort ASC, CreateTime DESC", param)?.ToList() ?? new List<ProjectModel>();
            }
        }

        /// <summary>
        /// 获取项目总数
        /// </summary>
        /// <param name="userIds">用户ID列表</param>
        /// <param name="name">项目名称（可选）</param>
        /// <returns></returns>
        public int GetCount(List<long> userIds, string name = "")
        {
            var whereStr = new StringBuilder(" WHERE IsDel = @IsDel AND IsValid = @IsValid ");
            object param = new
            {
                IsDel = FlagEnum.HadZore.GetHashCode(),
                IsValid = FlagEnum.HadOne.GetHashCode()
            };

            if (userIds != null && userIds.Count > 0)
            {
                whereStr.Append(" AND UserId IN @UserIds ");
                if (!string.IsNullOrEmpty(name))
                {
                    whereStr.Append(" AND ProjectName LIKE @Name ");
                    param = new
                    {
                        IsDel = FlagEnum.HadZore.GetHashCode(),
                        IsValid = FlagEnum.HadOne.GetHashCode(),
                        UserIds = userIds.ToArray(),
                        Name = $"%{name}%"
                    };
                }
                else
                {
                    param = new
                    {
                        IsDel = FlagEnum.HadZore.GetHashCode(),
                        IsValid = FlagEnum.HadOne.GetHashCode(),
                        UserIds = userIds.ToArray()
                    };
                }
            }
            else if (!string.IsNullOrEmpty(name))
            {
                whereStr.Append(" AND ProjectName LIKE @Name ");
                param = new
                {
                    IsDel = FlagEnum.HadZore.GetHashCode(),
                    IsValid = FlagEnum.HadOne.GetHashCode(),
                    Name = $"%{name}%"
                };
            }

            using (var conn = SqlConnectionHelper.GetOpenConnection())
            {
                return conn.RecordCount<ProjectModel>(whereStr.ToString(), param);
            }
        }

        /// <summary>
        /// 保存项目信息
        /// </summary>
        /// <param name="model">项目模型</param>
        /// <returns>项目ID</returns>
        public long SaveModel(ProjectModel model)
        {
            if (model == null) return 0;
            using (var conn = SqlConnectionHelper.GetOpenConnection())
            {
                if (model.Id > 0)
                {
                    // 更新
                    conn.Update(model);
                    return model.Id;
                }
                else
                {
                    // 添加
                    return conn.Insert<long, ProjectModel>(model);
                }
            }
        }

        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="id">项目ID</param>
        public void DelModel(long id)
        {
            if (id < 1) return;
            var model = Get(id);
            if (model == null) return;
            model.IsDel = FlagEnum.HadOne;
            model.UpdateTime = DateTime.Now;
            using (var conn = SqlConnectionHelper.GetOpenConnection())
            {
                conn.Update(model);
            }
        }

        /// <summary>
        /// 检查项目名称是否存在
        /// </summary>
        /// <param name="projectName">项目名称</param>
        /// <param name="userId">用户ID</param>
        /// <param name="excludeId">排除的项目ID（编辑时使用）</param>
        /// <returns></returns>
        public bool IsProjectNameExists(string projectName, long userId, long? excludeId = null)
        {
            var whereStr = new StringBuilder(" WHERE ProjectName = @ProjectName AND UserId = @UserId AND IsDel = @IsDel ");
            object param;

            if (excludeId.HasValue)
            {
                whereStr.Append(" AND Id != @ExcludeId ");
                param = new
                {
                    ProjectName = projectName,
                    UserId = userId,
                    IsDel = FlagEnum.HadZore.GetHashCode(),
                    ExcludeId = excludeId.Value
                };
            }
            else
            {
                param = new
                {
                    ProjectName = projectName,
                    UserId = userId,
                    IsDel = FlagEnum.HadZore.GetHashCode()
                };
            }

            using (var conn = SqlConnectionHelper.GetOpenConnection())
            {
                var count = conn.RecordCount<ProjectModel>(whereStr.ToString(), param);
                return count > 0;
            }
        }
    }
}